package com.czy.ekp.gen;


import cn.hutool.core.util.ObjectUtil;
import freemarker.template.Template;
import lombok.extern.slf4j.Slf4j;

import java.io.StringWriter;
import java.util.List;
import java.util.Map;

@Slf4j
public abstract class TemplateCodeGenerator implements CodeGenerator {

    private StringWriter writer = new StringWriter();
    private Template template;

    public TemplateCodeGenerator(Template template) {
        this.template = template;
    }

    public abstract Map generateParameterMap(ModuleVo moduleVo);

    public FieldVo getKeyField(List<FieldVo> fields){
        for(FieldVo field : fields){
            if(field.isKey()){
                return field;
            }
        }
        return null;
    }

    @Override
    public boolean generate(ModuleVo module){

        ModuleVo moduleVo = module.clone();

        if(moduleVo.getFields() != null && moduleVo.getFields().size() > 0){
            moduleVo.setKeyField(getKeyField(moduleVo.getFields()));
        }

        if(moduleVo.getKeyField() == null){
            log.error("module must has key field !");
            return false;
        }

        try{
            template.process(generateParameterMap(moduleVo), writer);
            writer.flush();
        }catch (Exception e){
            e.printStackTrace();
        }
        return true;
    }

    public boolean generateWithoutKey(ModuleVo module){

        ModuleVo moduleVo = module.clone();

        try{
            template.process(generateParameterMap(moduleVo), writer);
            writer.flush();
        }catch (Exception e){
            e.printStackTrace();
        }

        return true;
    }

    @Override
    public StringBuffer toBuffer(){
        return writer.getBuffer();
    }

    @Override
    public String toString(){
        return writer.getBuffer().toString();
    }
}
